package com.piece.core.authentication.handler;

import com.piece.core.web.authority.token.TokenServices;
import com.piece.core.framework.constant.CookieConstants;
import com.piece.core.framework.constant.ExceptionAuthConstants;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.util.basic.I18nUtil;
import com.piece.core.framework.util.string.JsonUtil;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.web.authority.AuthorityFactory;
import com.piece.core.web.cookie.CookieUtil;
import com.piece.core.web.util.AuthenticationUtil;
import com.piece.core.web.util.ServletUtil;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.Authentication;
import org.springframework.util.Assert;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LogoutSuccessHandler implements org.springframework.security.web.authentication.logout.LogoutSuccessHandler {

    @Lazy
    @Resource
    private TokenServices tokenServices;

    @Resource
    private AuthorityFactory authorityFactory;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        Assert.notNull(tokenServices, "tokenServices must be set");

        // 清空token
        String token = authorityFactory.get().extractToken(request);
        if (StringUtil.isNotEmpty(token)) {
            tokenServices.revokeToken(token);
        }

        //清空Session
        CookieUtil.deleteCookie(request, response, CookieConstants.SESSION_KEY);
        CookieUtil.deleteCookie(request, response, CookieConstants.TENANT_KET);

        // 记录登出日志
        if (null != authentication) {
            AuthenticationUtil.getInstance(request).logoutSuccessLog(authentication.getName());
        }

        String redirectUrl = request.getParameter("target");
        if (ServletUtil.isAjaxRequest(request)) {
            ServletUtil.renderString(response, JsonUtil.toJson(AjaxResponse.success(I18nUtil.message(ExceptionAuthConstants.LOGOUT_SUCCESS), redirectUrl)));
        } else {
            redirectUrl = (null == redirectUrl) ? request.getContextPath() : request.getContextPath() + redirectUrl;
            response.sendRedirect(redirectUrl);
        }
    }
}
